import { defineStore } from 'pinia';
import { studentLogin, teacherLogin } from '../api/user';
import router from '../router';
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
    loginTime: localStorage.getItem('loginTime') || null
  }),
  getters: {
    isLoggedIn: (state) => !!state.userInfo,
    userId: (state) => state.userInfo?.id,
    username: (state) => state.userInfo?.username,
    role: (state) => state.userInfo?.role,
    realName: (state) => state.userInfo?.realName,
    avatar: (state) => {
      if (!state.userInfo?.avatar) {
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
      }

      // 如果已经是完整URL，直接返回
      if (state.userInfo.avatar.startsWith('http')) {
        return state.userInfo.avatar;
      }

      // 前端开发环境修复：如果是以/avatar开头的路径，需要加上后端基础URL
      if (state.userInfo.avatar.startsWith('/avatar')) {
        return 'http://localhost:8080' + state.userInfo.avatar;
      }

      // 其他情况使用默认头像
      return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
    },
    // 检查登录是否过期
    isLoginExpired: (state) => {
      if (!state.loginTime) return true;
      // 24小时过期
      const expirationTime = 24 * 60 * 60 * 1000;
      return (new Date().getTime() - parseInt(state.loginTime)) > expirationTime;
    }
  },
  actions: {
    async login(loginForm, role) {
      try {
        console.log(`尝试${role}登录:`, loginForm.username);

        // 根据角色选择不同的登录接口
        const loginFn = role === 'student' ? studentLogin : teacherLogin;
        const response = await loginFn(loginForm);

        console.log('登录响应:', response);

        // 请求成功并返回了用户信息
        if (response.code === 200 && response.data) {
          // 验证返回的用户角色是否与期望的一致
          if (response.data.role !== role) {
            ElMessage.error(`该账号不是${role === 'student' ? '学生' : '教师'}账号`);
            return false;
          }

          // 保存用户信息
          this.userInfo = response.data;
          localStorage.setItem('userInfo', JSON.stringify(response.data));

          // 记录登录时间
          const now = new Date().getTime();
          this.loginTime = now.toString();
          localStorage.setItem('loginTime', now.toString());

          console.log('登录成功，保存用户信息:', this.userInfo.username);

          // 跳转到相应角色的首页
          router.push(`/${role}/dashboard`);
          return true;
        }

        return false;
      } catch (error) {
        console.error('登录失败:', error);
        ElMessage.error('登录失败: ' + (error.message || '未知错误'));
        return false;
      }
    },

    logout() {
      console.log('用户登出:', this.userInfo?.username);
      this.userInfo = null;
      this.loginTime = null;
      localStorage.removeItem('userInfo');
      localStorage.removeItem('loginTime');
      router.push('/login');
      ElMessage.success('已退出登录');
    },

    // 检查登录状态是否有效
    checkLogin() {
      if (!this.userInfo) {
        return false;
      }

      if (this.isLoginExpired) {
        console.log('登录已过期，清除用户信息');
        this.logout();
        return false;
      }

      return true;
    },

    // 刷新登录时间
    refreshLoginTime() {
      if (this.userInfo) {
        const now = new Date().getTime();
        this.loginTime = now.toString();
        localStorage.setItem('loginTime', now.toString());
        console.log('刷新登录时间');
      }
    }
  }
});
